package com.lagou.demo1;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/*
任务1:
idea代码编写入门案例，要求至少java或scala版本一种实现方式
实现步骤：
1、读取数据源
2、处理数据源
a、将读到的数据源文件中的每一行根据空格切分
b、将切分好的每个单词拼接1
c、根据单词聚合（将相同的单词放在一起）
d、累加相同的单词（单词后面的1进行累加）
3、保存处理结果
 */
public class WordCountBatch {
    public static void main(String[] args) throws Exception {
        ExecutionEnvironment executionEnvironment = ExecutionEnvironment.getExecutionEnvironment();
        DataSet<String> text = executionEnvironment.readTextFile("src/data/words.txt");

        FlatMapOperator<String, Tuple2<String, Long>> maped = text.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] words = s.split(" ");
                for (String word : words) {
                    collector.collect(Tuple2.of(word, 1L));
                }
            }
        });
        AggregateOperator<Tuple2<String, Long>>  sum = maped.groupBy(0).sum(1);

        sum.writeAsCsv("src/data/words_result1.txt","\n","").setParallelism(1);
       // 触发执行程序
        executionEnvironment.execute("wordcount batch process");


    }
}
